<template>
  <div class="tinymce-container" :style="{ width: containerWidth }">
    <textarea :id="tinymceId" ref="elRef"></textarea>
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/silver/theme'
import 'tinymce/icons/default'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/anchor'
import 'tinymce/plugins/autolink'
import 'tinymce/plugins/autosave'
import 'tinymce/plugins/code'
import 'tinymce/plugins/codesample'
import 'tinymce/plugins/directionality'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/hr'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/link'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/media'
import 'tinymce/plugins/nonbreaking'
import 'tinymce/plugins/noneditable'
import 'tinymce/plugins/pagebreak'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/print'
import 'tinymce/plugins/save'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/tabfocus'
import 'tinymce/plugins/template'
import 'tinymce/plugins/textpattern'
import 'tinymce/plugins/visualblocks'
import 'tinymce/plugins/visualchars'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/image'
import 'tinymce/plugins/table'
import 'tinymce/plugins/charmap'
import 'tinymce/plugins/emoticons'
import 'tinymce/plugins/emoticons/js/emojis'
import { toolbar, plugins } from './tinymce'
import request from '@/utils/request'

export default {
  name: 'Tinymce',
  props: {
    value: {
      type: String,
      default: ''
    },
    height: {
      type: [Number, String],
      default: 400
    },
    width: {
      type: [Number, String],
      default: 'auto'
    },
    toolbar: {
      type: Array,
      default: () => toolbar
    },
    plugins: {
      type: Array,
      default: () => plugins
    },
    options: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      tinymceId: 'tinymce-' + Date.now() + Math.random().toString(36).substr(2, 9),
      editor: null,
      isInitialized: false,
      fullscreen: false
    }
  },
  computed: {
    containerWidth() {
      const width = this.width
      if (typeof width === 'number') {
        return `${width}px`
      }
      return width
    },
    initOptions() {
      const publicPath = process.env.NODE_ENV === 'production' ? '/sjjn' : ''
      return {
        selector: `#${this.tinymceId}`,
        height: this.height,
        toolbar: this.toolbar,
        menubar: 'file edit insert view format table',
        plugins: this.plugins.join(' '),
        language_url: `${publicPath}/resource/tinymce/langs/zh_CN.js`,
        language: 'zh_CN',
        branding: false,
        promotion: false,
        statusbar: true,
        elementpath: false,
        relative_urls: false,
        remove_script_host: false,
        convert_urls: false,
        resize: true,
        // 字体大小选项
        fontsize_formats: '12px 14px 16px 18px 20px 24px 28px 32px 36px',
        // 段落格式
        block_formats: '段落=p; 一级标题=h1; 二级标题=h2; 三级标题=h3; 四级标题=h4; 五级标题=h5; 六级标题=h6; 代码块=pre',
        default_link_target: '_blank',
        link_title: false,
        object_resizing: true,
        // 配置皮肤
        skin_url: `${publicPath}/resource/tinymce/skins/ui/oxide`,
        content_css: `${publicPath}/resource/tinymce/skins/ui/oxide/content.min.css`,
        // 内容样式
        content_style: `
          body { 
            font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
            font-size: 14px; 
            line-height: 1.8;
            padding: 15px;
            color: #333;
            background: #fff;
          }
          p { margin: 0 0 10px; }
          img { max-width: 100%; height: auto; }
          table { border-collapse: collapse; width: 100%; }
          table td, table th { border: 1px solid #ddd; padding: 8px; }
        `,
        // 图片上传
        images_upload_handler: (blobInfo, success, failure) => {
          const formData = new FormData()
          formData.append('file', blobInfo.blob(), blobInfo.filename())

          request({
            url: '/common/upload',
            method: 'post',
            data: formData,
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(res => {
            if (res.code === 200) {
              success("http://www.worldskillsmuseum.cn/apiv1/contentgw"+ res.fileName)
            } else {
              failure('上传失败: ' + (res.msg || '未知错误'))
            }
          }).catch(err => {
            failure('上传失败: ' + err.message)
          })
        },
        ...this.options,
        setup: (editor) => {
          this.editor = editor
          editor.on('init', () => {
            this.initSetup()
          })
        }
      }
    }
  },
  watch: {
    value(newVal) {
      if (this.editor && this.isInitialized) {
        const currentContent = this.editor.getContent()
        if (newVal !== currentContent) {
          this.editor.setContent(newVal || '')
        }
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.initEditor()
      }, 30)
    })
  },
  beforeDestroy() {
    this.destroyEditor()
  },
  methods: {
    initEditor() {
      tinymce.init(this.initOptions)
        .then(() => {
          this.$emit('inited', this.editor)
        })
        .catch((err) => {
          console.error('TinyMCE初始化失败:', err)
          this.$emit('init-error', err)
        })
    },
    initSetup() {
      if (!this.editor) return

      this.isInitialized = true

      // 设置初始内容
      if (this.value) {
        this.editor.setContent(this.value)
      }

      // 监听内容变化
      this.editor.on('change keyup undo redo', () => {
        const content = this.editor.getContent()
        this.$emit('input', content)
        this.$emit('change', content)
      })

      // 监听全屏状态
      this.editor.on('FullscreenStateChanged', (e) => {
        this.fullscreen = e.state
      })
    },
    destroyEditor() {
      if (this.editor) {
        tinymce.remove(`#${this.tinymceId}`)
        this.editor = null
        this.isInitialized = false
      }
    },
    getContent() {
      return this.editor ? this.editor.getContent() : ''
    },
    setContent(content) {
      if (this.editor && this.isInitialized) {
        this.editor.setContent(content || '')
      }
    },
    insertContent(content) {
      if (this.editor && this.isInitialized) {
        this.editor.insertContent(content)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
  z-index: 1;

  ::v-deep .tox-tinymce {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }

  ::v-deep .tox-toolbar__primary {
    background: #f5f7fa;
  }

  ::v-deep .tox .tox-toolbar,
  ::v-deep .tox .tox-toolbar__overflow,
  ::v-deep .tox .tox-toolbar__primary {
    background: #f5f7fa;
  }

  ::v-deep .tox-editor-header {
    border-bottom: 1px solid #dcdfe6;
  }

  ::v-deep .tox-statusbar {
    border-top: 1px solid #dcdfe6;
  }
}
</style>

<style lang="scss">
/* 全局样式，修复 TinyMCE 弹出层的 z-index 问题 */
.tox-tinymce-aux {
  z-index: 9999 !important;
}

.tox.tox-silver-sink.tox-tinymce-aux {
  z-index: 9999 !important;
}

.tox-dialog-wrap,
.tox-dialog,
.tox-menu,
.tox-toolbar,
.tox-collection {
  z-index: 9999 !important;
}
</style>